package AES;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


public class AESUtil128 {
	public  static String encrypt(String password,String encryptMessage) throws Exception{
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes());
			kgen.init(128, random);
			SecretKey secretKey1 = kgen.generateKey(); 
			byte[] enCodeFormat1 = secretKey1.getEncoded();
			Cipher cipher1 = Cipher.getInstance("AES"); 
			SecretKeySpec key1 = new SecretKeySpec(enCodeFormat1, "AES");
			cipher1.init(Cipher.ENCRYPT_MODE,key1); 
			byte[] result =cipher1.doFinal(encryptMessage.getBytes("UTF-8")); 
			return new String(Base64.encodeBase64(result),"UTF-8");
		}
	
	
	public static String decrypt(String password,String decryptmessageByte) throws Exception{
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			random.setSeed(password.getBytes("UTF-8"));
			kgen.init(128, random);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] messageByte = cipher.doFinal(Base64.decodeBase64(decryptmessageByte));
			return new String(messageByte, "UTF-8");
	}
	public static void main(String[] args) throws Exception {
		String xml="hello world";
		String encryptString = encrypt("c631f32d871d0618",xml);
		String decryptString = decrypt("c631f32d871d0618",encryptString);
		System.out.println("加密数据: "+encryptString);
		System.out.println("解密数据: "+decryptString);
	}
	}
